import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
import { login } from '@/api/user'

NProgress.configure({ showSpinner: false })

// 重定向白名单
const whiteList = []

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()
  if (hasToken) {
    const hasGetUserInfo = store.getters.userInfo
    if (hasGetUserInfo) {
      next()
    } else {
      try {
        await store.dispatch('user/getInfo')
        next()
      } catch (error) {
        await store.dispatch('user/resetToken')
        Message.error(error || 'Has Error')
        login()
        NProgress.done()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      login()
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
